using MediatR;
using RBAC.Domain.WarehouseManagement;
using RBAC.ErrorCode;
using RBAC.Interstructrue.Base;
using RBAC.Read.Api.Application.Command.ERP.WarehouseManagement;
using Dapper;
using Microsoft.Extensions.Logging;

namespace RBAC.Read.Api.Application.Handler.ERP.WarehouseManagement
{
    public class GetWarehouseByIdCommandHandler : IRequestHandler<GetWarehouseByIdCommands, APIResult<WarehouseList>>
    {
        private readonly IDbConnectionFactory _connectionFactory;
        private readonly ILogger<GetWarehouseByIdCommandHandler> _logger;

        public GetWarehouseByIdCommandHandler(IDbConnectionFactory connectionFactory, ILogger<GetWarehouseByIdCommandHandler> logger)
        {
            _connectionFactory = connectionFactory;
            _logger = logger;
        }

        public async Task<APIResult<WarehouseList>> Handle(GetWarehouseByIdCommands request, CancellationToken cancellationToken)
        {
            var result = new APIResult<WarehouseList>();
            try
            {
                if (request.WarehouseListId <= 0)
                {
                    result.Code = APIEnums.Fail;
                    result.Msg = "参数无效：WarehouseListId 必须大于 0";
                    return result;
                }

                using var conn = _connectionFactory.CreateConnectionWithRetry();
                const string sql = "SELECT * FROM WarehouseList WHERE Id = @Id AND IsDeleted = 0";
                var warehouse = await conn.QueryFirstOrDefaultAsync<WarehouseList>(sql, new { Id = request.WarehouseListId });

                if (warehouse == null)
                {
                    result.Code = APIEnums.Fail;
                    result.Msg = "未找到对应的仓库信息";
                    result.Data = null;
                    return result;
                }

                result.Code = APIEnums.Success;
                result.Msg = "查询成功";
                result.Data = warehouse;
                return result;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "查询仓库信息失败, Id: {Id}", request.WarehouseListId);
                result.Code = APIEnums.Fail;
                result.Msg = "查询失败：" + ex.Message;
                result.Data = null;
                return result;
            }
        }
    }
}
